package org.study.itcast;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import static org.study.ByteBufferUtil.debugAll;


/**
 * @author: jzhou
 * @date: 2024/4/19-23:05
 * @version: 1.0
 * @description: spark3.3-study
 */
@Slf4j
public class ActualPractice {
    public static void main(String[] args) {
//        scatteringReads();
//        gatheringWrites();
        test();
    }

    /**
     * 集中写
     */
    private static void gatheringWrites() {
        try (RandomAccessFile file = new RandomAccessFile("netty-demo/3parts.txt", "rw")) {
            FileChannel channel = file.getChannel();
            ByteBuffer d = ByteBuffer.allocate(4);
            ByteBuffer e = ByteBuffer.allocate(4);
            channel.position(11);

            d.put(new byte[]{'f', 'o', 'u', 'r'});
            e.put(new byte[]{'f', 'i', 'v', 'e'});
            d.flip();
            e.flip();
            debugAll(d);
            debugAll(e);
            channel.write(new ByteBuffer[]{d, e});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 分散读
     */
    private static void scatteringReads() {

        try (RandomAccessFile file = new RandomAccessFile("netty-demo/3parts.txt", "rw")) {
            FileChannel channel = file.getChannel();
            ByteBuffer a = ByteBuffer.allocate(3);
            ByteBuffer b = ByteBuffer.allocate(3);
            ByteBuffer c = ByteBuffer.allocate(5);
            channel.read(new ByteBuffer[]{a, b, c});
            a.flip();
            b.flip();
            c.flip();
            debugAll(a);
            debugAll(b);
            debugAll(c);
        } catch (IOException e) {
            log.error("", e);
        }
    }

    /**
     * 黏包和半包
     * 但由于某种原因这些数据在接收时，被进行了重新组合，例如原始数据有3条为
     * Hello,world\n
     * I'm zhangsan\n
     * How are you?\n
     * 变成了下面的两个 byteBuffer (黏包，半包)
     * Hello,world\nI'm zhangsan\nHo
     * w are you?\n
     * 现在要求你编写程序，将错乱的数据恢复成原始的按 \n 分隔的数据
     */
    private static void test() {
        ByteBuffer source = ByteBuffer.allocate(32);
        //                     11            24
        source.put("Hello,world\nI'm zhangsan\nHo".getBytes());
        split(source);

        source.put("w are you?\nhaha!\n".getBytes());
        split(source);
    }

    private static void split(ByteBuffer source) {
        source.flip();
        int limit = source.limit();
        for (int i = 0; i < limit; i++) {
            if (source.get(i) == '\n'){
                int bufferSize = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(bufferSize);
                for (int j = 0; j < bufferSize; j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }
        source.compact();
    }


}
